package net.wicp.tams.common.connector.executor.impl;

import java.util.HashMap;
import java.util.Map;

import com.alibaba.fastjson.JSONObject;

import net.wicp.tams.common.connector.beans.CusDynaBean;
import net.wicp.tams.common.connector.config.AbstractConfigClass;
import net.wicp.tams.common.connector.config.xmlParser.XMLNameSpace;
import net.wicp.tams.common.connector.executor.IConfigManager;
import net.wicp.tams.common.exception.param.Request;

/***
 * 协议的配置文件管理
 * 
 * @author zhoujunhui
 *
 */
public abstract class AbsConfigManager implements IConfigManager {

	protected final String dir;// 存放xml文件的目录
	private final static Map<String, AbstractConfigClass> configmap = new HashMap<String, AbstractConfigClass>();

	public AbsConfigManager() {
		this.dir = "connector";
	}

	public AbsConfigManager(String dir) {
		this.dir = dir;
	}

	public CusDynaBean getInputBean(String appKey) {
		return getConfig(appKey).newInputBean();
	}

	@Override
	public CusDynaBean getInputBeanInputBody(JSONObject inputBody) {
		String appKey = inputBody.getJSONObject(XMLNameSpace.ControlInfo).getString(Request.requestCommand);
		CusDynaBean inputBean = getInputBean(appKey);
		inputBean.setByJson(inputBody);
		return inputBean;
	}

	@Override
	public String getAppkeyByInputBody(JSONObject inputBody) {
		String appKey = inputBody.getJSONObject(XMLNameSpace.ControlInfo).getString(Request.requestCommand);
		return appKey;
	}

	@Override
	public final AbstractConfigClass getConfig(String appKey) {
		AbstractConfigClass retobj = configmap.get(appKey);
		if (retobj == null) {
			retobj = createConfig(appKey);
			if (retobj != null) {
				configmap.put(appKey, retobj);
			}
		}
		return retobj;
	}

	@Override
	public synchronized void refresh() {
		configmap.clear();
	}

	protected abstract AbstractConfigClass createConfig(String appKey);

}
